package com.eostoken.eos_wallet.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.eostoken.eos_wallet.MainActivity;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.AccountNames;
import com.eostoken.eos_wallet.bean.ImportWalletMode;
import com.eostoken.eos_wallet.bus.ToWallet;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.mvp.callback.CommonCallback;
import com.eostoken.eos_wallet.ui.activity.QrcodeScanActivity;
import com.eostoken.eos_wallet.utils.ClipboardUtils;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.fredy.mvp.BasePresenter;
import com.fredy.mvp.BaseView;
import com.fredy.mvp.Model;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import party.loveit.bip44forandroidlibrary.core.ECKey;
import party.loveit.bip44forandroidlibrary.utils.Bip44Utils;
import party.loveit.eosforandroidlibrary.Ecc;

import static com.eostoken.eos_wallet.utils.Constants.BUS_TO_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.IMPORT_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.INTENT_EXTRA_KEY_QR_SCAN;
import static com.eostoken.eos_wallet.utils.Constants.TO_IMPORT_WALLET_MNEMONIC;
import static com.eostoken.eos_wallet.utils.Constants.TO_IMPORT_WALLET_PRIVATEKEY;

public class ImportWalletFragment extends BaseFragment {

    @BindView(R.id.topbar)
    QMUITopBarLayout topbar;
    @BindView(R.id.importWalletKeyEt)
    AppCompatEditText importWalletKeyEt;
    @BindView(R.id.passwordEt)
    AppCompatEditText passwordEt;
    @BindView(R.id.confirmPasswordEt)
    AppCompatEditText confirmPasswordEt;
    @BindView(R.id.promptMessageEt)
    AppCompatEditText promptMessageEt;
    @BindView(R.id.clauseCheckBox)
    AppCompatCheckBox clauseCheckBox;
    @BindView(R.id.imporStarttBtn)
    QMUIRoundButton imporStarttBtn;
    @BindView(R.id.tabSegment)
    QMUITabSegment mTabSegment;
    @BindView(R.id.importTipsTv)
    AppCompatTextView importTipsTv;

    private int type;//3:
    private boolean isAgree = false;
    private String privatekey;
    private String password;
    private List<String> walletNameList;
    private String publicKey;
    private String hint;
    private String[] arr;
    private boolean isPrivatekeyImport = true;
    private List<String> mnemonicCode;
    private QMUIBottomSheet qmuiBottomSheet;
    private String mnemonics;
    private int currIndex = 0;

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_import_wallet;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        type = bundle.getInt(Constants.EXTRA_IMPORT_WALLET_WAY, 0);
        privatekey = bundle.getString(Constants.EXTRA_WALLET_PRIVATEKEY, "");
        String scanResult = bundle.getString(INTENT_EXTRA_KEY_QR_SCAN, "");
        if (!ObjectUtils.isEmpty(scanResult)) {
            ImportWalletMode importWalletMode = GsonUtils.fromJson(scanResult, ImportWalletMode.class);
            if (importWalletMode.getType().intValue() == TO_IMPORT_WALLET_PRIVATEKEY) {
                privatekey = importWalletMode.getPrivateKey();
                isPrivatekeyImport = true;
                currIndex = 0;
            } else {
                mnemonics = importWalletMode.getMnemonic();
                isPrivatekeyImport = false;
                currIndex = 1;
            }

            importWalletKeyEt.setText(isPrivatekeyImport ? privatekey : mnemonics);
        }
        arr = new String[]{getString(R.string.str_privatekey), getString(R.string.str_mnemonic_word)};
//        mnemonicCode = new ArrayList<>();
    }

    @Override
    public void onResume() {
        super.onResume();
        QMUIStatusBarHelper.setStatusBarDarkMode(getActivity());
        BarUtils.setStatusBarColor(getActivity(), ColorUtils.getColor(R.color.app_color_blue));
        BarUtils.setStatusBarLightMode(getActivity(), false);
    }

    @Override
    protected void initView(View contentView) {
        topbar.setTitle(StringUtils.getString(R.string.str_import_account));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getFragmentManager().getBackStackEntryCount() < 1) {
                    finish();
                } else {
                    FragmentUtils.pop(getFragmentManager());
                }
            }
        });
        topbar.addRightImageButton(R.mipmap.qrcode_icon_2, R.id.topbar_right_change_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
        initTabAndPager();
        clauseCheckBox.setText(Html.fromHtml(StringUtils.getString(R.string.str_agreement_clause_2)));

        clauseCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAgree = isChecked;
            }
        });
        updateView();
    }

    private void updateView() {
        importTipsTv.setText(isPrivatekeyImport ? getString(R.string.str_import_privatekey_tips) : getString(R.string.str_import_mnemonics_tips));
        importWalletKeyEt.setHint(isPrivatekeyImport ? getString(R.string.str_input_privatekey) : getString(R.string.str_import_mnemonics_hint));
    }

    private void initTabAndPager() {
        QMUITabBuilder builder = mTabSegment.tabBuilder().setGravity(Gravity.CENTER);
        for (int i = 0; i < arr.length; i++) {
            mTabSegment.addTab(builder.setText(arr[i]).build(getActivity()));
        }
        mTabSegment.setMode(QMUITabSegment.MODE_FIXED);
        int indicatorHeight = QMUIDisplayHelper.dp2px(getActivity(), 2);
        mTabSegment.setIndicator(new QMUITabIndicator(indicatorHeight, false, false));
        mTabSegment.selectTab(currIndex);
        mTabSegment.addOnTabSelectedListener(new QMUITabSegment.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int index) {
                currIndex = index;
                isPrivatekeyImport = currIndex == 0;
                updateView();
            }

            @Override
            public void onTabUnselected(int index) {

            }

            @Override
            public void onTabReselected(int index) {
            }

            @Override
            public void onDoubleTap(int index) {
                mTabSegment.clearSignCountView(index);
            }
        });
    }

    /**
     * 开始扫码
     */
    public void startQrCode() {
        PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(UtilsTransActivity activity, ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(getActivity(), shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        Intent intent = new Intent(getActivity(), QrcodeScanActivity.class);
                        startActivityForResult(intent, Constants.REQUEST_SCAN_CODE);
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {

                    }
                }).request();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.dTag("onScanQRCodeSuccess==", "result = " + resultCode);
        switch (requestCode) {
            case Constants.REQUEST_SCAN_CODE:
                if (!ObjectUtils.isEmpty(data)) {
                    Bundle bundle = data.getExtras();
                    String scanResult = bundle.getString(INTENT_EXTRA_KEY_QR_SCAN);
                    if (scanResult.contains("\"type\":\"" + TO_IMPORT_WALLET_PRIVATEKEY + "\"") || scanResult.contains("\"type\":" + TO_IMPORT_WALLET_PRIVATEKEY) ||
                            scanResult.contains("\"type\":\"" + TO_IMPORT_WALLET_MNEMONIC + "\"") || scanResult.contains("\"type\":" + TO_IMPORT_WALLET_MNEMONIC)) {
                        ImportWalletMode importWalletMode = GsonUtils.fromJson(scanResult, ImportWalletMode.class);
                        if (importWalletMode.getType().intValue() == TO_IMPORT_WALLET_MNEMONIC) {
                            mnemonics = importWalletMode.getMnemonic();
                            isPrivatekeyImport = false;
                            currIndex = 1;
                        } else {
                            privatekey = importWalletMode.getPrivateKey();
                            isPrivatekeyImport = true;
                            currIndex = 0;
                        }
                        mTabSegment.selectTab(currIndex);
                        updateView();
                    } else {
                        privatekey = "";
                        mnemonics = "";
                        DialogHelper.showLongMessageDialog(getActivity(), getString(R.string.str_prompt_message), scanResult, getString(android.R.string.cancel), getString(R.string.str_copy), new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        }, new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                ClipboardUtils.copyText(scanResult);
                                ToastUtils.showShort(StringUtils.getString(R.string.str_copy_success));
                                dialog.dismiss();
                            }
                        }).show();
                    }
                    importWalletKeyEt.setText(isPrivatekeyImport ? privatekey : mnemonics);
                }
                break;
            default:
        }
    }

    @Override
    public Model createModel() {
        return null;
    }

    @Override
    public BaseView createView() {
        return null;
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void finishRefresh() {

    }

    @OnClick({R.id.imporStarttBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imporStarttBtn:
                try {
                    password = passwordEt.getText().toString().trim();
                    String confirmPassword = confirmPasswordEt.getText().toString().trim();
                    String text = importWalletKeyEt.getText().toString().trim();

                    if (ObjectUtils.isEmpty(text)) {
                        ToastUtils.showLong(isPrivatekeyImport ? R.string.str_input_privatekey : R.string.str_import_mnemonics_hint);
                        return;
                    }
                    if (ObjectUtils.isEmpty(password)) {
                        ToastUtils.showLong(R.string.str_input_password);
                        return;
                    }
                    if (password.getBytes().length < 6) {
                        ToastUtils.showLong(R.string.str_hint_password);
                        return;
                    }

                    if (!ObjectUtils.equals(password, confirmPassword)) {
                        ToastUtils.showLong(R.string.str_inconformity_password);
                        return;
                    }
                    if (!isAgree) {
                        ToastUtils.showLong(R.string.str_protocol_not_checked);
                        return;
                    }
                    if (isPrivatekeyImport) {
                        privatekey = text;
                    } else {
                        String[] arr = text.split(" ");
                        List<String> list = Arrays.asList(arr);
                        mnemonicCode = new ArrayList<>();
                        for (String s : list) {
                            if (!ObjectUtils.isEmpty(s.trim())) {
                                mnemonicCode.add(s);
                            }
                        }
                        BigInteger pri = Bip44Utils.getPathPrivateKey(mnemonicCode, Constants.EOS_PATH);
                        party.loveit.bip44forandroidlibrary.core.ECKey ecKey = ECKey.fromPrivate(pri);
                        privatekey = Ecc.seedPrivate(pri);
                        publicKey = Ecc.privateToPublic(privatekey);
                    }
                    hint = promptMessageEt.getText().toString().trim();

                    WalletUtils.importWallet(getActivity(), privatekey, new CommonCallback() {
                        @Override
                        public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                            AccountNames accountNames = (AccountNames) data;
                            List<String> accountNameList = accountNames.getAccount_names();
                            qmuiBottomSheet = DialogHelper.showSimpleBottomSheetList(getActivity(), false, true, false, getString(R.string.str_select_account),
                                    null, accountNameList, true, true, new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                                            dialog.dismiss();
                                            showLoading();
                                            String accountName = accountNameList.get(position);
                                            WalletUtils.queryWallet(getActivity(), accountName, new CommonCallback() {
                                                @Override
                                                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                                                    //已存在
                                                    ToastUtils.showLong(successMsg);
                                                    hideLoading();
                                                }

                                                @Override
                                                public void onFailure(String msg, int responseFailCode) {
                                                    hideLoading();
                                                    //不存在
                                                    ToastUtils.showLong(successMsg);
                                                    MgpWallet mgpWallet = WalletUtils.addWallet(getActivity(), accountName, password, privatekey, publicKey, mnemonicCode, hint);
                                                    doAfterPermissionsGranted(mgpWallet);
                                                }
                                            });
                                        }
                                    });
                            qmuiBottomSheet.show();
//                                MgpWallet mgpWallet = WalletUtils.addWallet(getActivity(), accountname, password, privatekey, publicKey, originList, hint);

//                                ToastUtils.showLong(successMsg);
//                                doAfterPermissionsGranted();
                        }

                        @Override
                        public void onFailure(String msg, int responseFailCode) {
                            ToastUtils.showLong(msg);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort(isPrivatekeyImport ? R.string.str_invalid_privatekey : R.string.str_invalid_mnemonics);
                }
                break;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (qmuiBottomSheet != null) {
            qmuiBottomSheet.dismiss();
        }
        hideLoading();
    }

    private void doAfterPermissionsGranted(MgpWallet wallet) {
        Intent intent = new Intent(getActivity(), MainActivity.class);
        intent.putExtra("type", "import_wallet");
        ActivityUtils.startActivity(intent);
        BusUtils.post(BUS_TO_WALLET, new ToWallet(wallet, IMPORT_WALLET));
        FragmentUtils.removeAll(getFragmentManager());
        finish();
    }
}
